<template>
<!--    文章内容-->
    <article ref="preview" id="preview-md" class="article-con preview">

    </article>
</template>

<script>
    import marked from 'marked'
    import Prism from 'prismjs' // 代码高亮

    import Cache from '@/utils/cache/index'
    let cache = new Cache()
    cache.setCacheType = 'sessionStorage'

    import constant from '@/utils/constant'
    const { CACHE_ARTICLE_ALL } = constant

    import { getArticle } from '@/api/article/'
    export default {
        props: {
            articleId: {
                type: [String, Number],
                default: '',
            },
        },
        mounted() {
            let { articleId: id } = this.$route.params

            this.getArticleData(id)
        },
        methods: {
            getArticleData (id) {
                cache.getCache(CACHE_ARTICLE_ALL, async (data) => {

                    let article = data && data.some(item => item.id === id) ? this.cacheArticle(data, id) : (await this.getArticleFn(id))

                    let nodePreview = this.$refs['preview']

                    nodePreview.innerHTML = marked(article.content)

                    // 添加行号
                    let aCode = nodePreview.querySelectorAll('code')
                    aCode.forEach((item) => {
                        item.className.includes('language') && item.classList.add('line-numbers')
                    })

                    Prism.highlightAll()
                })
            },
            cacheArticle (data, id) {
               return data.find(item => Number(id) == item.id)
            },
            async getArticleFn (id) {
                let { result } = await getArticle(id)

                return result && result[0]
            },
        },
    }
</script>

<style scoped lang="scss">
    .article-con {

    }

    .preview {
        width: 100%;
        text-align: left;

    }
</style>
